import os
import time
import json
import shutil
import undetected_chromedriver as uc
import selenium
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from public import *
from tools import *
mlog = MyLogger("rpa")
config = ConfigManager()

def retry(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for i in range(times):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    print("e:",e)
                    if i == times - 1:
                        raise e
        return wrapper
    return decorator

class rpa_service(object):
    def __init__(self):
        self.driver = None
        self.init_driver()
    
    def max_window(self):
        self.driver.maximize_window()

    def init_driver(self):
        """_summary_
            初始化driver
        """
        options = uc.ChromeOptions()
        # options.add_argument("--headless")  # 启用无头模式
        options.add_argument("--disable-gpu")  # 禁用GPU加速（某些系统需要）
        options.add_argument("--no-sandbox")
        options.user_data_dir = config.get("browser","user_data_dir")
        driver_path = config.get("browser","driver_path")
        driver_port = int(config.get("browser","driver_port"))
        browser_path = config.get("browser","browser_path")

        driver = uc.Chrome(
            driver_executable_path=driver_path,
            browser_executable_path=browser_path,
            options=options,
            enable_cdp_events=True,
            port=driver_port
        )
        self.driver = driver


        # with open("./cookie.json", "r") as f:
        #     cookies = json.loads(f)
        #     for cookie in cookies:
        #         driver.add_cookie(cookie)

        # # 加载 LocalStorage
        # with open("local_storage.json", "r") as f:
        #     local_storage = json.load(f)
        #     driver.execute_script(f"Object.assign(window.localStorage, {local_storage});")

        # 刷新页面以应用状态
        driver.refresh()
        return True
    
    def get(self,url):
        """_summary_
            获取页面
        """
        self.driver.get(url)
        return True
    
    @retry(3)
    def get_element(self,xpath):
        """_summary_
            获取元素
        """
        element = WebDriverWait(self.driver, timeout=30,poll_frequency=0.5).until(
                        EC.visibility_of_any_elements_located((By.XPATH, xpath))
                    )
        return element[0]
    
    @retry(3)
    def click_element(self,ele):
        ele.click()
        return True

class rpa_server(object):
    def __init__(self):
        self.rpa_service = rpa_service()


        self.file_download_path = config.get("rpa","file_download_path")
        self.file_save_path = config.get("rpa","file_save_path")
    
    def load_iframe(self):
        ele = self.rpa_service.get_element(".//iframe[@id='wiki-doc-iframe']")
        if ele:
            iframe_url = ele.get_attribute("src")
            return iframe_url

    def down_load_file(self):
        mlog.info("下载文档...")
        element = self.rpa_service.get_element(".//button[@data-testid='doc-header-more-button']")
        element.click()
        mlog.info("下载文档(1/3)...")
        button2 = self.rpa_service.get_element(".//div[text()='下载到本地']")
        button2.click() 
        mlog.info("下载文档(2/3)...")
        button3 = self.rpa_service.get_element(".//div[text()='Word(.docx)']")
        button3.click()
        mlog.info("下载文档(3/3)...")
        return True

    def clean_download_path(self):
        try:
            if not os.path.exists(self.file_download_path):
                return
                
            files = os.listdir(self.file_download_path)
            if not files:
                return
                
            os.makedirs(self.file_save_path, exist_ok=True)
            
            for filename in files:
                src_path = os.path.join(self.file_download_path, filename)
                if os.path.isfile(src_path):
                    dest_path = os.path.join(self.file_save_path, filename)
                    shutil.move(src_path, dest_path)
                    mlog.info(f"成功移动文件: {filename}")
        
        except Exception as e:
            mlog.error(f"文件移动失败: {str(e)}")
        
        return True

    def check_file(self):
        """_summary_
            检查文件是否下载下来
        """
        for i in range(60):
            files = os.listdir(self.file_download_path)
            files = [_ for _ in files if _.endswith("crdownload") is False]
            if not files:
                time.sleep(1)
            else:
                return os.path.join(self.file_download_path, files[0])
        return False

    def run(self,dingding_doc_link,request_id):
        """_summary_
            执行任务
        """
        try:
            # 清除文档链接
            self.clean_download_path()
            mlog.info("已清除下载目录")
            # self.rpa_service.max_window()
            # 1.获取钉钉文档链接
            self.rpa_service.driver.get(dingding_doc_link)
            mlog.info("访问链接")
            # 2.提取iframe内置链接
            iframe_link = self.load_iframe()
            mlog.info(f"iframe_link:[{iframe_link}]")
            # 3.获取文件
            self.rpa_service.get(iframe_link)
            mlog.info("访问iframe链接")
            # 4.下载文件
            self.down_load_file()
            # 5.检查文件是否下载下来
            if (file:=self.check_file()):
                return file
            else:
                return False
        except Exception as e:
            mlog.error(f"rpa 程序异常！！ {str(e)}")
            filepath = "./file/screenshot"
            if os.path.exists(filepath) is False:os.makedirs(filepath)
            file_save_path = os.path.join(f"./file/screenshot",f"{request_id}_{int(time.time())}")
            self.rpa_service.driver.save_screenshot(file_save_path)
            mlog.error(f"[rpa已截图][{os.path.abspath(file_save_path)}]")
            print(self.rpa_service.driver.title)
            if self.rpa_service.driver.title == "www.google.com":
                mlog.error(f"文档链接不对,打开后的标题是:",self.rpa_service.driver.title)
                self.rpa_service.driver.save_screenshot(os.path.join(f"./file/screenshot",f"{dingding_doc_link}_{int(time.time())}"))
                return 0
            return False

if __name__ == "__main__":
    rpa = rpa_server()
    rpa.run()
    # while True:
    #     task = {
    #         "prd_link":"https://alidocs.dingtalk.com/i/nodes/20eMKjyp81R7pXXmsYMoxajlWxAZB1Gv?iframeQuery=utm_source%3Dportal%26utm_medium%3Dportal_recent&rnd=0.8926047418701994",
    #         "prd_level":"B"
    #     }
    #     check = input("测试")
    #     file = rpa.run(task)
    #     # D:\project\zmn_aiprd_project\file\download\BIZ_5023736_产品方案_20250124.docx
    #     print(file)